import React, { useState } from "react";
import { useAuth } from "../context/AuthProvider";
import { login } from "../api/user";
import { Link } from "react-router-dom";
import { message, Button, Form, Input } from 'antd';

const Login = () => {
    const {setUser} = useAuth();
    const [loading,setLoading] = useState(false);

    const onFinish = (values) => {
        setLoading(true)
        login({userName:values.userName,password:values.password})
        .then(res => {
            console.log(res)

            if(res.code === '200') {
                message.success(res.msg)
                setUser(res.data)
            }
        })
        .catch(err => {
            message.error('出错！')
        })
        .finally(() => {
            setLoading(false)
        })
    };

	return <div>
		<Form
                layout='vertical'
                style={{
                    width:400,
                    margin:'50px auto'
                }}
                onFinish={onFinish}
            >
                <Form.Item
                    label="用户名"
                    name="userName"
                    rules={[
                        {
                            required: true,
                            message: '请输入用户名！',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="密码"
                    name="password"
                    rules={[
                        {
                            required: true,
                            message: '请输入密码！',
                        },
                    ]}
                >
                    <Input.Password />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit" block shape='round' loading={loading}>
                        登录
                    </Button>
                </Form.Item>

                <Link to='/register'>去注册</Link>
            </Form>
	</div>
}

export default Login;